package com.yunxi.service.dubboService.impl.sto;

import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.activiti.service.ActivitiManageDubboService;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.model.order.PmsVehicleStock;
import com.yunxi.model.sto.*;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.sto.*;
import com.yunxi.sto.pojo.*;
import com.yunxi.sto.service.PartnerVehicleTradeDubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 渠道商车辆买卖 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-08-30
 */

public class PartnerVehicleTradeDubboServiceImpl implements PartnerVehicleTradeDubboService {

    @Autowired
    @Qualifier(value = "partnerVehicleTradeServiceImpl")
    PartnerVehicleTradeService partnerVehicleTradeService;

    @Autowired
    @Qualifier(value = "partnerVehicleTradeDetailServiceImpl")
    PartnerVehicleTradeDetailService partnerVehicleTradeDetailService;

    @Autowired
    @Qualifier(value = "activitiManageDubboServiceImpl")
    ActivitiManageDubboService activitiManageDubboService;

    @Autowired
    @Qualifier(value = "approveHisServiceImpl")
    ApproveHisService approveHisService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    @Qualifier(value = "stoStockInPlanServiceImpl")
    StoStockInPlanService stoStockInPlanService;

    @Autowired
    @Qualifier(value = "stoStockOutPlanServiceImpl")
    StoStockOutPlanService stoStockOutPlanService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateService;

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockMService;


    @Override
    public PartnerVehicleTradeVO getById(String id) throws Exception {
        PartnerVehicleTradeVO detailById = partnerVehicleTradeService.getDetailById(id);
        if(detailById == null || StringUtils.isEmpty(detailById.getTradeId()))throw new Exception("操作失败,无法根据id:"+id+"找到对应记录");
        List<PartnerVehicleTradeDetailListVO> list = partnerVehicleTradeService.detailList(id);
        detailById.setVinDetailList(list);
        return detailById;
    }

    @Override
    public void saveOrUpdate(PartnerVehicleTradeVO partnerVehicleTradeVO, LoginInfo loginInfo) throws Exception {
        List<PartnerVehicleTradeDetailAddVO> vinList = partnerVehicleTradeVO.getVinList();
        if(vinList == null || vinList.size() <= 0)throw new Exception("操作失败,买卖车辆数量为0!");
        PartnerVehicleTrade partnerVehicleTrade = new PartnerVehicleTrade();
        BeanUtils.copyProperties(partnerVehicleTradeVO, partnerVehicleTrade);
        partnerVehicleTrade.setTradeQuanlity(vinList.size());
        partnerVehicleTrade.setApproveStatus(10);
        if(StringUtils.isEmpty(partnerVehicleTrade.getInAreaCode()) || StringUtils.isEmpty(partnerVehicleTrade.getOutAreaCode())){
            //卖方大区代码
            String outAreaCode = partnerVehicleTradeService.queryAreaCodeByPartnerCode(partnerVehicleTradeVO.getOutPartnerCode());
            //买方大区代码
            String inAreaCode = partnerVehicleTradeService.queryAreaCodeByPartnerCode(partnerVehicleTradeVO.getPartnerCode());
            partnerVehicleTrade.setInAreaCode(inAreaCode);
            partnerVehicleTrade.setOutAreaCode(outAreaCode);
        }
        partnerVehicleTradeService.saveOrUpdate(partnerVehicleTrade);
        String tradeId = partnerVehicleTrade.getTradeId();
        //1.根据tradeId删除详情
        QueryWrapper<PartnerVehicleTradeDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TRADE_ID",tradeId);
        partnerVehicleTradeDetailService.remove(queryWrapper);
        for(PartnerVehicleTradeDetailAddVO vo : vinList){
            //2.新增详情
            PartnerVehicleTradeDetail partnerVehicleTradeDetail = new PartnerVehicleTradeDetail();
            partnerVehicleTradeDetail.setTradeId(tradeId);
            partnerVehicleTradeDetail.setVin(vo.getVin());
            partnerVehicleTradeDetail.setRemark(vo.getRemark());
            partnerVehicleTradeDetailService.saveOrUpdate(partnerVehicleTradeDetail);
            //变更车辆为非共享车 20190904 cy
            QueryWrapper<VehicleOffline> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("VIN",vo.getVin());
            VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper1);
            if(vehicleOffline != null){
                vehicleOffline.setIsShare(0);
                vehicleOfflineService.saveOrUpdate(vehicleOffline);
            }
        }
        //启动流程
//        activitiManageDubboService.start("1000006","52504",partnerVehicleTrade.getTradeId(),loginInfo);
        //插入提交审核历史
        ApproveHis approveHis = new ApproveHis();
        approveHis.setBusinessId(partnerVehicleTrade.getTradeId());
        approveHis.setDictType("Trade_ApproveStatus");
        approveHis.setHandleType("10");
        approveHis.setHandleTime(new Date());
        approveHis.setHandleUser(loginInfo.getUserCode());
        approveHisService.saveOrUpdate(approveHis);
    }

    @Override
    public void removeById(String id) {
        partnerVehicleTradeService.removeById(id);
    }

    @Override
    public PageInfo<PartnerVehicleTradeVO> findPageByVO(PartnerVehicleTradeVO partnerVehicleTradeVO, Integer pageNum, Integer pageSize) throws Exception {
        PageInfo<PartnerVehicleTradeVO> pageInfo = partnerVehicleTradeService.pageByVo(partnerVehicleTradeVO, pageNum, pageSize);
        return pageInfo;
    }

    /**
     * 审核列表
     * @param partnerVehicleTradeVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<PartnerVehicleTradeVO> saleFromManager(PartnerVehicleTradeVO partnerVehicleTradeVO, Integer pageNum, Integer pageSize,Integer approveType) throws Exception {
        partnerVehicleTradeVO.setApproveType(approveType);
        //大区代码
//        String areaCode = partnerVehicleTradeService.queryAreaCodeByPartnerCode(partnerVehicleTradeVO.getOutPartnerCode());
        Integer approveType1 = partnerVehicleTradeVO.getApproveType();
        String areaCode = partnerVehicleTradeService.queryAreaCodeByUserCode(partnerVehicleTradeVO.getUserCode());
        if(approveType1 == 2){
            partnerVehicleTradeVO.setOutAreaCode(areaCode);
        }
        else if(approveType1 == 3){
            partnerVehicleTradeVO.setInAreaCode(areaCode);
        }
        PageInfo<PartnerVehicleTradeVO> pageInfo = partnerVehicleTradeService.saleFromManager(partnerVehicleTradeVO, pageNum, pageSize);
        return pageInfo;
    }

    /**
     * 审核历史分页
     * @param partnerVehicleTradeVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<PartnerVehicleTradeApproveHisVO> approveHis(PartnerVehicleTradeVO partnerVehicleTradeVO, Integer pageNum, Integer pageSize) throws Exception {
        String tradeId = partnerVehicleTradeVO.getTradeId();
        if(StringUtils.isEmpty(tradeId))throw new Exception("操作失败,主键ID为空!");
        PageInfo<PartnerVehicleTradeApproveHisVO> pageInfo = partnerVehicleTradeService.approveHis(partnerVehicleTradeVO, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    public void removeByListVo(List<PartnerVehicleTradeVO> partnerVehicleTradeVOList) throws Exception {
        partnerVehicleTradeService.removeByListVo(partnerVehicleTradeVOList);
    }

    @Override
    public List listByVo(PartnerVehicleTradeVO partnerVehicleTradeVO) {
        return partnerVehicleTradeService.listByVo(partnerVehicleTradeVO);
    }

    /**
     * 买卖车辆详情列表
     * @param tradeId
     * @return
     * @throws Exception
     */
    @Override
    public List<PartnerVehicleTradeDetailListVO> detailList(String tradeId) throws Exception {
        return partnerVehicleTradeService.detailList(tradeId);
    }

    /**
     * 审核
     * @param partnerVehicleTradeApproveVO
     * @throws Exception
     */
    @Override
    public void approve(PartnerVehicleTradeApproveVO partnerVehicleTradeApproveVO,LoginInfo loginInfo) throws Exception {
        PartnerVehicleTrade partnerVehicleTrade = partnerVehicleTradeService.getById(partnerVehicleTradeApproveVO.getTradeId());
        if(partnerVehicleTrade == null)throw new Exception("操作失败,无法根据主键:"+partnerVehicleTradeApproveVO.getTradeId()+"找到对应记录!");
        Integer approveStatus = partnerVehicleTrade.getApproveStatus();
        if(approveStatus != null && approveStatus.equals(8))throw new Exception("操作失败,已总部审核完成不可再次审核!");
        partnerVehicleTrade.setApproveStatus(partnerVehicleTradeApproveVO.getApproveStatus());
        partnerVehicleTrade.setReturnReason(partnerVehicleTradeApproveVO.getReturnReason());
        partnerVehicleTradeService.saveOrUpdate(partnerVehicleTrade);

        //插入审核历史
        ApproveHis approveHis = new ApproveHis();
        approveHis.setBusinessId(partnerVehicleTrade.getTradeId());
        approveHis.setDictType("Trade_ApproveStatus");
        approveHis.setHandleType(partnerVehicleTradeApproveVO.getApproveStatus().toString());
        approveHis.setHandleTime(new Date());
        approveHis.setHandleUser(loginInfo.getUserCode());
        approveHis.setRemark(partnerVehicleTradeApproveVO.getReturnReason());
        approveHisService.saveOrUpdate(approveHis);

        //总部审核通过,生成出入库历史
        if(partnerVehicleTradeApproveVO.getApproveStatus().equals(8)){
            //卖家渠道代码
            String outPartnerCode = partnerVehicleTrade.getOutPartnerCode();
            //买家渠道代码
            String partnerCode = partnerVehicleTrade.getPartnerCode();
            QueryWrapper<PartnerVehicleTradeDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TRADE_ID",partnerVehicleTrade.getTradeId());
            List<PartnerVehicleTradeDetail> list = partnerVehicleTradeDetailService.list(queryWrapper);
            if(list != null && list.size() > 0){
                for (PartnerVehicleTradeDetail partnerVehicleTradeDetail : list){
                    //生成已完成的入库计划
                    StoStockInPlan stoStockInPlan = new StoStockInPlan();
                    stoStockInPlan.setBillState("2");
                    stoStockInPlan.setVin(partnerVehicleTradeDetail.getVin());
                    stoStockInPlan.setStockInType("1");
                    stoStockInPlan.setStockInDate(new Date());
                    stoStockInPlan.setBillCreateTime(new Date());
                    stoStockInPlan.setPlanStockInDate(new Date());
                    String stockInNo = codeCreateService.createCode("SIP", 4);
                    stoStockInPlan.setStockInPlanNo(stockInNo);
                    stoStockInPlanService.saveOrUpdate(stoStockInPlan);

                    //生成已完成的出库计划
                    StoStockOutPlan stoStockOutPlan = new StoStockOutPlan();
                    String sop = codeCreateService.createCode("SOP", 4);
                    stoStockOutPlan.setStockOutPlanNo(sop);
                    stoStockOutPlan.setVin(partnerVehicleTradeDetail.getVin());
                    stoStockOutPlan.setBillState("4");
                    stoStockOutPlan.setStockOutType("1");
                    stoStockOutPlan.setPlanStockOutDate(new Date());
                    stoStockOutPlan.setStockOutDate(new Date());
                    stoStockOutPlanService.saveOrUpdate(stoStockOutPlan);
                }
            }

            //变更车辆库存所属渠道商
            QueryWrapper<PartnerVehicleTradeDetail> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("TRADE_ID",partnerVehicleTradeApproveVO.getTradeId());
            List<PartnerVehicleTradeDetail> list1 = partnerVehicleTradeDetailService.list(queryWrapper1);
            if(list1 != null && list.size() > 0){
                for (PartnerVehicleTradeDetail bo : list1){
                    QueryWrapper<PmsVehicleStock> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("VIN",bo.getVin());
                    PmsVehicleStock vehicleStock = vehicleStockMService.getOne(queryWrapper2);
                    if(vehicleStock != null){
                        vehicleStock.setPartnerCode(partnerCode);//买方渠道代码
                        vehicleStockMService.saveOrUpdate(vehicleStock);
                    }
                }
            }
        }
    }
}
